<!-- 用户终端绑定 -->
<template>
  <div class="view-container">
    <div>
      <component
        @click="toBack"
        :is="useRenderIcon(ArrowLeftFill)"
        class="w-[30px] h-[30px]"
      />
    </div>
    <div class="zh-query-box">
      <QueryBox 
      ref="queryBox"
      :attr="queryAttr"
      :content="queryProperty"
      @query="toQuery"
      ></QueryBox>
    </div>
    <div class="zh-table-box">
      <Table 
      ref="table1Ref"
      :data="tableData" 
      :globalOperate="globalOperate"
      :globalTab="globalTab"
      :selectChangeEvent="selectChangeEvent"
      :selectAllChangeEvent="selectAllChangeEvent"
      :columns="tableColumns" 
      :rowOperate="rowOperate"
      :rowOperateProperty="rowOperateProperty"
      :showPrint="showToolbox.showPrint"
      :showImport="showToolbox.showImport"
      :showExport="showToolbox.showExport"
      :showTool="showToolbox.showTool"
      @pageChange="handlePageChange"
      :page="page"
      ></Table>
    </div>
    <el-dialog
      v-model="dialogParams.visible"
      :width="dialogParams.width"
      :title="dialogParams.title"
      @close="handleClose()"
      >
      <transition 
        name="cube" mode="out-in"
      >
      <div class="second" style="width: 100%;">
        <el-form :model="userForm" ref="userFormRef" label-width="auto">
          <el-form-item prop="uid" label="身份证号">
            <p>{{userForm.uid}}</p>
          </el-form-item>
          <el-form-item prop="mid" label="终端编号">
            <div class="flex gap-2 flex-wrap">
              <p v-if="dialogParams.opr == 'editExpire'">{{ userForm.mid }}</p>
              <el-input v-model="userForm.mid" v-else></el-input>
            </div>
          </el-form-item>
          <!-- <el-form-item prod="status" label="绑定关系">
            <el-switch
              v-model="userForm.status"
            />
          </el-form-item> -->
          <el-form-item prod="expire" label="过期时间">
            <el-date-picker
              v-model="userForm.expire"
              type="datetime"
              placeholder="请选择过期时间"
            />
          </el-form-item>
          <!-- <el-form-item prop="mids" label="终端编号">
            <div class="flex gap-2 flex-wrap">
              <el-tag v-for="tag in userForm.mids" :key="tag" closable :type="tag" @close="handleCloseTag(tag)">
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item> -->
        </el-form>
      </div>
      </transition>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button
            type="primary"
            @click="execute()"
          >确 定</el-button>
        </div>
      </template>
      </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import ArrowLeftFill from "@iconify-icons/ri/arrow-left-s-line.js";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Table from "@/components/Table/table.vue"
import QueryBox from "@/components/QueryBox/queryBox.vue";
import {
  apiListUserMid,
  apiListClient,
  apiEditUserMid,
} from "@/api/user";
import { useRoute,useRouter } from 'vue-router'

import { ref, watch, onMounted, h, nextTick, reactive } from "vue";
import { ElButton, ElDatePicker, ElIcon, ElMessage, ElMessageBox, ElPopconfirm, ElRadioButton, ElRadioGroup, ElSwitch, ElTag, FormInstance } from "element-plus";

defineOptions({
  name: "User2Mid",
});


const route = useRoute()
const router = useRouter()

onMounted(async () => {
  userForm.value.uid = route.query.uid
  defaultExpire.value = getLastMonth()
  initPage()
  initTableProperty()
})

const parseDate = (dateString) => {
    const [datePart, timePart] = dateString.split(' ');
    const [year, month, day] = datePart.split('-');
    const [hours, minutes, seconds] = timePart.split(':');
  
    // 构建日期对象，注意月份是从 0 开始的
    return new Date(year, month - 1, day, hours, minutes, seconds);
}

const getLastMonth = () => {
  let currentDate = new Date('2025-03-31');

  // 加一个月
  currentDate.setMonth(currentDate.getMonth() + 1);
  return currentDate
}

const queryBox = ref()

const initTableProperty = () => {
  initRowOperate()
  tableColumns.value = wholeTableColumns
  globalOperate.value = wholeGlobalOperate
  globalTab.value = wholeGlobalTab
}

const showToolbox = ref({
  showPrint: false,
  showImport: false,
  showExport: false,
  showTool: false
})

const rowOperateProperty = ref({
  width: '250',
  show: false
})

const page = ref({
  page:1,
  pageSize:10,
  total:0
})

const table1Ref = ref()
const tableData = ref([]);

const tableColumns = ref([])
const wholeTableColumns = [
  // {
  //   type: 'checkbox',
  //   width: '40'
  // },
  {
    align:'left',
    title:'终端编号',
    field: 'mid',
    minWidth: '120px'
  },
  // {
  //   align:'left',
  //   title:'终端标识',
  //   field:'serverflag'
  // },
  // {
  //   align: 'left',
  //   title: '绑定状态',
  //   field: 'status',
  //   render : (dom,props) => {
  //     return (
  //       h('div', { class: "operate-box" }, [
  //          h(ElSwitch, {
  //               style: '--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949',
  //               modelValue: props.row.status === 1,  
  //               onChange: ()=> toChangeBindTerm(props.row)
  //             }),
  //       ]
  //           )
  //     )
  //   }
  // },
  {
    align: 'left',
    title: '过期时间',
    field: 'expire',
  },
]

const defaultExpire = ref(new Date())
const changeDefaultExpire = (val) => {
  defaultExpire.value = val
}

const globalTab = ref('')
const wholeGlobalTab = {
  render : () => {
    return (
      h('div',{class:"operate-box"},
        [h('span','默认过期时间：'),h(ElDatePicker,
          {
            type: 'date',
            disabled: false,
            modelValue: defaultExpire.value,
            "onUpdate:modelValue": (val) => changeDefaultExpire(val)
          }),
          // h('div', { style: 'margin-left: 15px'},[
          //   h(ElButton,
          // {
          //   type: 'primary',
          //   disabled: userForm.value.mids.length === 0,
          //   modelValue: defaultExpire.value,
          //   onClick: () => toBindTerm()
          //     }, () => '批量绑定')]),
        h('div', { style: 'margin-left: 15px'},[
            h(ElButton,
          {
            type: 'primary',
            // disabled: userForm.value.mids.length === 0,
            modelValue: defaultExpire.value,
            onClick: () => toBindTerm()
          },()=>'新增绑定')])]
      )
    )
  }
}

const necessaryQuery = ref({
})

const globalOperate = ref({})
const wholeGlobalOperate = {
}
const operationList = {
  render : (dom,props) => {
    return (
      h('div',{class:"operate-box"},
        [
        h(ElButton,{
          type: 'success',
          plain: true,
          onClick: ()=>toChangeBindTerm(props.row)
        }, () => "解绑终端"),
        h(ElButton,{
            type: 'warning',
            plain: true,
            onClick: ()=>toEditExpire(props.row)
          }, () => "修改过期时间")
      ]
      )
    )
  }
}

const selectAllChangeEvent = (val) => {
  userForm.value.mids = val.records.map(item => item.mid)
}

const selectChangeEvent = (val) => {
  userForm.value.mids = val.records.map(item => item.mid)
}
const rowOperate = ref({})

const initRowOperate = () => {
  rowOperateProperty.value.show = true
  rowOperate.value = operationList
}  

// 分页
const handlePageChange = (val) => {
  page.value = val
  toQuery(queryBox.value.propertyValue)
}

const queryAttr = ref({
  leftBoxWidth: 84,
  rightBoxWidth: 16
})

const queryProperty = [
  {
    label: '终端编号',
    type: 'input', // 默认有 input,selectbox,date
    labelWidth: 25,
    valueWidth: 75,
    elementName: 'mid',  // 调用方的元素属性名称
    elementValueType: 'string', // 默认 strng,number,array
    elementDefaultValue: '',
    elementWidth: '900',
    elementProperty:{
      placeholder: '请输入终端编号'
    }
  },
  // {
  //   label: '绑定状态',
  //   type: 'select', // 默认有 input,selectbox,date
  //   labelWidth: 4,
  //   valueWidth: 6,
  //   elementName: 'status',  // 调用方的元素属性名称
  //   elementValueType: 'number', // 默认 strng,number,array
  //   elementDefaultValue: '',
  //   elementOptions:[
  //     {
  //       label: '默认',
  //       value: 0
  //     },
  //     {
  //       label: '绑定',
  //       value: 1
  //     },
  //     {
  //       label: '不绑定',
  //       value: 2
  //     }
  //   ],
  //   elementProperty:{}
  // },
]

const toQuery = async (data) => {
  var queryParam: Object  = {
  }
  if (data.status) queryParam.status = data.status
  if (data.mid !== '') queryParam.mid = data.mid
  getTableData(queryParam)
}

// 查询
const getTableData = async (queryParam) => {
  const table = await apiListUserMid({
    "userMidRequest": {
      page_num: page.value.page,
      uid: userForm.value.uid,
      page_size: page.value.pageSize,
      ...queryParam 
    }
  })
  if (table.code === 200) {
    tableData.value = table.listUserMidResponse?.data;
    page.value =
    {
      total: table.listUserMidResponse.page?.total,
      page: page.value.page,
      pageSize: page.value.pageSize
    }
  }
}

watch(
  () => tableData.value,
  () => {
  }
)

const userFormRef = ref()

const initPage = async () => {
  getTableData({
  });
}

// 弹窗相关
const userForm = ref({
  expire: new Date(),
  mids: [],
  mid:'',
  uid: '',
  status: false,
});

const dialogParams = ref({
  title: '绑定终端',
  width: '640',
  visible: false,
  opr: 'bindTerm'
})

const resetUserForm = () => {
  userForm.value.mids = []
  userForm.value.mid = ''
  userForm.value.status = false
};

const handleClose = () => {
  resetUserForm()
  table1Ref.value.clearSeleted()
  dialogParams.value.visible = false
  dialogParams.value.title = '绑定终端'
}

const changeExpire = (val) => {
  userForm.value.expire = val
}

const toChangeBindTerm = async (row) => {
  try {
    const confirm = await ElMessageBox.confirm(`此操作将解除该终端绑定, 是否继续?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (confirm === 'confirm') {
      const form = {
        uid: row.uid,
        mids: [row.mid],
        expire: row.expire,
        status: 2
      }
      let res = await apiEditUserMid({ userMidRequest: form })
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleClose()
      } else {
        return
      }
      getTableData({
      })
      return
    }
  } catch (error) {
    console.log('error: ', error);
  }

  // console.log(confirm)
}

const toBindTerm = () => {
  dialogParams.value.visible = true
  dialogParams.value.title = '绑定终端'
  dialogParams.value.opr = 'bindTerm'
  dialogParams.value.width = '640'
  userForm.value.expire = defaultExpire.value
}

const toEditExpire = (row) => {
  dialogParams.value.visible = true
  dialogParams.value.title = '修改过期时间'
  dialogParams.value.opr = 'editExpire'
  dialogParams.value.width = '640'
  userForm.value.uid = row.uid
  userForm.value.mid = row.mid
  userForm.value.expire = row.expire
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const goBindTerm = async () => {
  let text = ""
  if (userForm.value.uid == "") text = "用户编号不能为空"
  // if (userForm.value.mids.length <= 0) text = "绑定终端不能为空"
  if (userForm.value.mid.length <= 0) text = "绑定终端不能为空"
  if (userForm.value.expire == null) text = "过期时间不能为空"
  if (text !== "") {
    ElMessage({
      type: 'warning',
      message: text
    })
    return
  }
  const form = {
    uid: userForm.value.uid,
    mids: [userForm.value.mid],
    expire: formatDate(userForm.value.expire),
    // status: userForm.value.status?1:2
    status: 1
  }
  return await apiEditUserMid({ userMidRequest: form })
}

const handleCloseTag = (val) => {
  if (userForm.value.mids.length <= 1) {
    ElMessage({
      type: 'warning',
      message:'至少保留一个终端信息'
    })
    return
  }
  userForm.value.mids = userForm.value.mids.filter(item=>item != val)
}

const toBack = () => {
  router.go(-1)
}

const execute = async () => {
  let res = null
  if (dialogParams.value.opr == 'bindTerm') {
    res = await goBindTerm()
  } else if (dialogParams.value.opr == 'editExpire') {
    res = await goBindTerm()
  }
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    handleClose()
  } else {
    return
  }
  getTableData({
  })
  return
}

</script>

<style lang="scss" scoped>
.view-container{
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}
.query-box{
  width: 100%;
  margin-top: 5px;
}
.zh-query-box {
  @apply p-4 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900 rounded my-2;
  border: 1px solid var(--table-border);
}
.zh-table-box {
  @apply p-4 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900 rounded my-2;
  border: 1px solid var(--table-border);
  height: 720px;
  overflow: hidden;
}
.first{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.dialog-left{
  width: 100%;
}
.dialog-right{
  width: 100%;
  padding-left:10px;
  max-height: 400px;
  overflow: auto;
}
.cube-enter-active,
.cube-leave-active {
	transition: all .7s;
}

.cube-enter-from,
.cube-leave-to {
	transform: translateY(0px) rotateX(40deg);
	opacity: 0;
}

.cube-enter-to,
.cube-leave-from {
	transform: translateY(0) rotateX(0deg);
	opacity: 1;
}
h4{
  text-indent: 1em;
}
.validate-col {
  padding-bottom: 17px;
}
.el-form-item.is-error {
  .ip_input_container{
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
}
::v-deep(.el-form){
  max-width: 800px !important;
}
.el-form-item--label-top .el-form-item__label{
  margin-bottom: 0px;
}
.el-form-item__label{
  font-size: 14px;
  font-weight: 500;
}
.sub-title{
  border: 1px solid rgb(229,230,235);
  padding: 10px;
  border-radius: 2px;
  transition: box-shadow .2s cubic-bezier(0,0,1,1);
}
.sub-title > .el-form-item__label{
  padding: 0px 0 0 0;
  font-size: 15px;
  font-weight: 600;
  padding-bottom: 10px;
}
.operate-box{
  display: flex;
  gap: 20px;
}
</style>
